import storage from "./storage";
import API from "./api";
import moment from "moment";
import notification from "src/utils/notification";
import fetch from "src/utils/fetch";
import Vue from "vue";

export function loadJs(src, callback) {
  let script = document.createElement("script");
  let head = document.getElementsByTagName("head")[0];
  let loaded;

  script.src = src;

  if (typeof callback === "function") {
    script.onload = script.onreadystatechange = function() {
      if (!loaded && (!script.readyState || /loaded|complete/.test(script.readyState))) {
        script.onload = script.onreadystatechange = null;
        loaded = true;
        callback();
        setTimeout(() => {
          script.parentNode.removeChild(script);
        }, 200);
      }
    };
  }
  head.appendChild(script);
}

export function sendReq(obj) {
  if (obj.showLoading) {
    window.CONTEXT.$store.commit("LOADING");
  }
  fetch({
    url: obj.url,
    type: "post",
    data: obj.params,
    isExport: obj.isExport ? obj.isExport : false,
    showRegionLoading: true,
    success: (data, obj1 = obj) => {
      obj.cb(data);
      if (obj1.showLoading) {
        window.CONTEXT.$store.commit("UNLOADING");
      }
      if (obj1.note) {
        notification.success("操作成功");
      }
    },
    error: (res, obj2 = obj) => {
      if (obj2.showLoading) {
        window.CONTEXT.$store.commit("UNLOADING");
      }
      obj.error && obj.error();
      notification.error(res.message);
    }
  });
}

export function clearLoginInfo() {
  cookie.clear();
  sessionStorage.clear();
  location.href = "http://nsso.zhonganonline.com/logout?service=za-xraise-ops&target=" + encodeURIComponent(location.origin + location.pathname + location.hash);
}
export const cookie = {
  set: function(key, val, time) {
    //设置cookie方法
    var date = new Date(); //获取当前时间
    var expiresDays = time; //将date设置为n天以后的时间
    date.setTime(date.getTime() + expiresDays * 3600 * 1000); //格式化为cookie识别的时间
    document.cookie = key + "=" + val + ";expires=" + date.toGMTString(); //设置cookie
  },
  get: function(key) {
    //获取cookie方法
    /*获取cookie参数*/
    var getCookie = document.cookie.replace(/[ ]/g, ""); //获取cookie，并且将获得的cookie格式化，去掉空格字符
    var arrCookie = getCookie.split(";"); //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中
    var tips; //声明变量tips
    for (var i = 0; i < arrCookie.length; i++) {
      //使用for循环查找cookie中的tips变量
      var arr = arrCookie[i].split("="); //将单条cookie用"等号"为标识，将单条cookie保存为arr数组
      if (key == arr[0]) {
        //匹配变量名称，其中arr[0]是指的cookie名称，如果该条变量为tips则执行判断语句中的赋值操作
        tips = arr[1]; //将cookie的值赋给变量tips
        break; //终止for循环遍历
      }
    }

    return tips;
  },
  del: function(key) {
    //删除cookie方法
    var date = new Date(); //获取当前时间
    date.setTime(date.getTime() - 10000); //将date设置为过去的时间
    document.cookie = key + "=v; expires =" + date.toGMTString(); //设置cookie
  },
  clear: function() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
      for (var i = keys.length; i--; ) document.cookie = keys[i] + "=0;expires=" + new Date(0).toUTCString();
    }
  }
};

export function copyJSONObj(obj) {
  return isJSON(obj, true) ? JSON.parse(JSON.stringify(obj)) : obj;
}
export function jsonPretty(obj) {
  return isJSON(obj.data, obj.isHideWarning) ? JSON.stringify(obj.data, "{}", 4) : obj.data;
}

export function isJSON(str, isHideDialog) {
  if (typeof str == "string") {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        isHideDialog == undefined && notification.error("不是标准的JSON格式数据,程序无法解析!");
        return false;
      }
    } catch (e) {
      // console.log('error：'+str+'!!!'+e);
      isHideDialog == undefined && notification.error("不是标准的JSON格式数据,程序无法解析!");
      return false;
    }
  }

  return true;
  // console.log('It is not a string!')
}

export function DateFormat(gmt, fmt) {
  if (gmt) {
    var d = new Date(gmt),
      year = d.getFullYear(),
      month = d.getMonth() + 1,
      day = d.getDate(),
      hour = d.getHours(),
      minute = d.getMinutes(),
      second = d.getSeconds();

    return year + "-" + Appendzero(month) + "-" + Appendzero(day) + " " + Appendzero(hour) + ":" + Appendzero(minute) + ":" + Appendzero(second);
  } else {
    return gmt;
  }

  function Appendzero(num) {
    return num < 10 ? "0" + num : num;
  }
}

/**
 * 将HTML Table数据导出成Excel文档
 *   string  tableId 表格ID
 *   string  downloadFileName 导出文档名
 */

export function tableExportExcel(data) {
  var blobObj = new Blob([data.fileContent]);
  // var blobObj = new Blob([data.fileContent], { type: "'text/csv';charset=utf-8" });

  if (window.navigator.msSaveBlob) {
    // IE 10+
    window.navigator.msSaveOrOpenBlob(blobObj, data.fileName);
    //$scope.DataNullEventDetails = true;
  } else {
    var link = document.createElement("a"); //create link download file
    link.href = window.URL.createObjectURL(blobObj); // set url for link download
    link.setAttribute("download", data.fileName); //set attribute for link created
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

function CompareObj(objA, objB, flag) {
  for (var key in objA) {
    if (!flag)
      //跳出整个循环
      break;
    if (!objB.hasOwnProperty(key)) {
      flag = false;
      break;
    }
    if (!isArray(objA[key])) {
      //子级不是数组时,比较属性值
      if (objB[key] != objA[key]) {
        flag = false;
        break;
      }
    } else {
      if (!isArray(objB[key])) {
        flag = false;
        break;
      }
      var oA = objA[key],
        oB = objB[key];
      if (oA.length != oB.length) {
        flag = false;
        break;
      }
      for (var k in oA) {
        if (!flag)
          //这里跳出循环是为了不让递归继续
          break;
        flag = CompareObj(oA[k], oB[k], flag);
      }
    }
  }
  return flag;
}

function isObj(object) {
  return object && typeof object == "object" && Object.prototype.toString.call(object).toLowerCase() == "[object object]";
}

function isArray(object) {
  return object && typeof object == "object" && object.constructor == Array;
}

function getLength(object) {
  var count = 0;
  for (var i in object) count++;
  return count;
}

export function Compare(objA, objB) {
  if (!isObj(objA) || !isObj(objB)) return false; //判断类型是否正确
  if (getLength(objA) != getLength(objB)) return false; //判断长度是否一致
  return CompareObj(objA, objB, true); //默认为true
}

/**
 * 工具函数
 * @Author   邬天美
 * @DateTime 2018-01-09
 */
/**
 * 移出json对象中的空项
 * @Author   邬天美
 * @DateTime 2018-01-10
 * @param    {[type]}   json [description]
 * @return   {[type]}        [description]
 */
export function filterEmpty(json, delArry) {
  let obj = {};
  let j;
  if (json) {
    for (j in json) {
      if (json[j] !== undefined || json[j] !== "") {
        obj[j] = json[j];
      }
    }
    if (delArry) {
      delArry.map(item => {
        delete obj[item];
      });
    }
  }
  return obj;
}
/**
 * 检测json是否为null
 * @Author   邬天美
 * @DateTime 2018-04-13
 * @param    {[type]}   json    [description]
 * @param    {[type]}   delArry [description]
 * @return   {[type]}           [description]
 */
export function checkJSONNull(json) {
  if (!json || !Object.keys(json).length) return true;
  for (var j in json) {
    if (json[j] !== undefined && json[j] !== "") {
      return false;
    }
  }
  return true;
}
/**
 * 移出url最后一个/
 * @Author   邬天美
 * @DateTime 2018-01-19
 * @param    {[type]}   url [description]
 * @return   {[type]}       [description]
 */
function removeLastGang(url) {
  let lastIndex = url.lastIndexOf("/");
  if (lastIndex >= 1 && lastIndex == url.length - 1) {
    //url最后还了 /
    url = url.substring(0, lastIndex);
  }
  return url;
}
/**
 * 设置查询参数
 * @Author   邬天美
 * @param    {[type]}   url    [description]
 * @param    {[json]}   searchFormParams 搜索框中的条件,包括临时输入,而未点击查询的参数
 * @param    {[json]}   routeParams 浏览器后面带的查询条件,已经进行查询的
 */
export function setSearchParams(url, searchFormParams = {}, routeParams = {}) {
  if (!url) return false;
  let allParams = storage.get(API.sessionKey.searchParams) || {};
  allParams[removeLastGang(url)] = { searchFormParams, routeParams };
  storage.set(API.sessionKey.searchParams, allParams);
}
/**
 * 获取查询参数
 * @Author   邬天美
 * @DateTime 2018-01-19
 * @param    {[type]}   url    [description]
 * @param    {[type]}   params [description]
 * @return   {[type]}          [description]
 */
export function getSearchParams(url) {
  if (!url) return false;
  let params = storage.get(API.sessionKey.searchParams) || {};
  let currentParams = params[removeLastGang(url)] || {};
  !currentParams.searchFormParams && (currentParams.searchFormParams = {});
  !currentParams.routeParams && (currentParams.routeParams = {});
  return currentParams;
}
/**
 * 把查询参数设置到浏览器地址上
 *
 * @Author   邬天美
 * @DateTime 2018-01-11
 * @param    {[this.$router]}   router    router对像
 * @param    {[string]}   path      路径
 * @param    {[type]}   params    要加到浏览器上的参数
 */
export function setRouter(router, path, params) {
  router.push({
    path,
    query: {
      ...params,
      times: Date.now()
    }
  });
}
/**
 * 验较身份证号码
 * @Author   邬天美
 * @DateTime 2018-01-10
 * @param    {[type]}   card [description]
 * @return   {[type]}        [description]
 */
export function checkIDCard(card) {
  if (!card) return true;
  var num = card.toUpperCase();
  //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
  if (!/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num)) {
    return false;
  }
  //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
  //下面分别分析出生日期和校验位
  var len, re;
  var birthday, sex;
  len = num.length;
  if (len == 15) {
    //获取出生日期
    birthday = "19" + card.substring(6, 8) + "-" + card.substring(8, 10) + "-" + card.substring(10, 12);
    //获取性别
    sex = parseInt(card.substr(14, 1)) % 2 == 1 ? "M" : "F";

    re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
    var arrSplit = num.match(re);

    //检查生日日期是否正确
    var dtmBirth = new Date("19" + arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
    var bGoodDay;
    bGoodDay = dtmBirth.getYear() == Number(arrSplit[2]) && dtmBirth.getMonth() + 1 == Number(arrSplit[3]) && dtmBirth.getDate() == Number(arrSplit[4]);
    if (!bGoodDay) {
      return false;
    } else {
      //将15位身份证转成18位
      //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
      var valnum;
      var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
      var arrCh = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2");
      var nTemp = 0,
        i;

      num = num.substr(0, 6) + "19" + num.substr(6, num.length - 6);
      for (i = 0; i < 17; i++) {
        nTemp += num.substr(i, 1) * arrInt[i];
      }
      num += arrCh[nTemp % 11];
    }
  } else if (len == 18) {
    //获取出生日期
    birthday = card.substring(6, 10) + "-" + card.substring(10, 12) + "-" + card.substring(12, 14);
    //获取性别
    sex = parseInt(card.substr(16, 1)) % 2 == 1 ? "M" : "F";

    re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
    var arrSplit = num.match(re);

    //检查生日日期是否正确
    var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
    var bGoodDay;
    bGoodDay = dtmBirth.getFullYear() == Number(arrSplit[2]) && dtmBirth.getMonth() + 1 == Number(arrSplit[3]) && dtmBirth.getDate() == Number(arrSplit[4]);
    if (!bGoodDay) {
      return false;
    } else {
      //检验18位身份证的校验码是否正确。
      //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
      var valnum;
      var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
      var arrCh = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2");
      var nTemp = 0,
        i;
      for (i = 0; i < 17; i++) {
        nTemp += num.substr(i, 1) * arrInt[i];
      }
      valnum = arrCh[nTemp % 11];
      if (valnum != num.substr(17, 1)) {
        return false;
      }
    }
  }

  return true;
}

/**
 * @description 格式化之后的数据
 * @author   曹清华
 * @DateTime 2018-01-17
 * @param formatSource 自定义来源
 * @param targetSource 格式化目标
 * @returns 格式化之后的数据
 */
export function format(formatSource, targetSource) {
  return formatSource[targetSource] ? formatSource[targetSource] : targetSource;
}

/**
 * @author 曹清华
 * @description 格式化为dateFormat时间格式
 * @param params 目标对象
 * @param sub 数组下标 同时表示 开始还是结束日期 0 start：开始 1 end：结束时间
 * @param type 自定义格式还是强制加的格式 force强制 custom 自定义
 */

export function format_yyy_mm_dd_hh_mm_ss(options) {
  let { params, type, sub } = options;
  if (params) {
    let dateFormat = "YYYY-MM-DD HH:mm:ss";
    let timeEnd = "";
    //强制格式化日期
    if (type === "force") {
      dateFormat = "YYYY-MM-DD";
      if (sub == "0") {
        timeEnd = " 00:00:00";
      } else if (sub == "1") {
        timeEnd = " 23:59:59";
      }
    }
    if (sub == "0" || sub == "1") {
      return params[sub] ? moment(params[sub]).format(dateFormat) + timeEnd : params[sub];
    } else {
      return params ? moment(params).format(dateFormat) + timeEnd : params;
    }
  } else {
    return "";
  }
}

/**
 * @author 曹清华
 * @description 格式化为dateFormat时间格式
 * @param params 目标对象
 */

export function format_yyy_mm_dd(params, format) {
  let type = format ? format : "YYYY-MM-DD";
  return params ? moment(params).format(type) : params;
}
/**
 * 下载保存的二进制文件流
 * @Author   邬天美
 * @DateTime 2018-03-20
 * @param    {[type]}   binary   [description]
 * @param    {[type]}   fileName [description]
 * @return   {[type]}            [description]
 */
export function downloadBinaryExcelFile(binary, fileName) {
  var data = new Blob([binary], { type: "application/msexcel,charset=utf-8;" });
  var downloadUrl = window.URL.createObjectURL(data);
  var anchor = document.createElement("a");
  anchor.href = downloadUrl;
  anchor.download = (fileName || "导出文件") + ".xls";
  anchor.click();
  window.URL.revokeObjectURL(data);
}

export function isEmptyObject( obj ) {
  var name;
  for ( name in obj ) {
    return false;
  }
  return true;
}

export function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  let str = null;
  if(r != null){
    let s = unescape(r[2]);
    if(s.substring(s.length - 1,s.length) === "/"){
      str = s.substring(0,s.length - 1)
    }else{
      str = s;
    }
  }
  return str;
}

export function changeURLArg(url,arg,arg_val){
  var pattern = arg+'=([^&]*)';
  var replaceText = arg+'='+arg_val; 
  if(url.match(pattern)){
    var tmp = '/('+ arg+'=)([^&]*)/gi';
    tmp = url.replace(eval(tmp),replaceText);
    return tmp;
  }else{ 
    if(url.match('[\?]')){ 
        return url+'&'+replaceText; 
    }else{ 
        return url+'?'+replaceText; 
    } 
  }
}